<template>
	<f7-page>
		<f7-navbar>
			<f7-nav-left>
				<f7-link  @click="$f7router.back()">
                    <f7-icon icon="icon-back" style="margin-left: 15px;"></f7-icon>
                </f7-link>
			</f7-nav-left>
			<f7-nav-title title="选择退回原因"></f7-nav-title>
		</f7-navbar>
		<f7-block strong inset style="margin-top:5px; margin-bottom:5px;">
            <f7-list>
                <f7-list-item v-for="(reason, i) in reasons" :title="reason" 
                	:radio="true" :checked="reason == form.backReasonValue" @click="changeBackReson(reason)"></f7-list-item>
                <f7-list-item v-show="sendBackRemarkShow">
                    <f7-input type="textarea" rows="2" placeholder="补充说明"
                              :value="sendBackRemark" @change="sendBackRemark = $event.target.value">
                    </f7-input>
                </f7-list-item>
                <f7-list-item>
                    <f7-list-item-cell>
                        <f7-list-item>
                			<TakePhoto ref="refTakePhoto" @photoAdd="photoAdd" @photoDelete="photoDelete"></TakePhoto>
            			</f7-list-item>
                    </f7-list-item-cell>
                </f7-list-item>
                <f7-list-item>
                    <f7-list-item-cell width="50">
                        <f7-button  big round @click="saveTemporary">暂存</f7-button>
                    </f7-list-item-cell>
                    <f7-list-item-cell width="50">
                        <f7-button  big round  @click="ensureSendBackSubmit">退回</f7-button>
                    </f7-list-item-cell>
                </f7-list-item>
            </f7-list>
        </f7-block>
	</f7-page>
</template>

<script>
import networkEvent from '@/mixins/networkEvent';
import back from '@/mixins/back.js';
import Common from "@/utils/Common.js";
import DateUtil from "@/utils/DateUtil.js";
import FileUtil from "@/utils/FileUtil.js";
import request from '@/utils/request';
import $ from 'jquery';
import events from 'events';
import { getUser, setUser, clearUser } from '@/utils/auth';
import { upload, uploadImage } from '@/utils/upload';
import TakePhoto from "@/components/TakePhoto.vue";

export default { 
	mixins: [networkEvent, back],
    components: {
        TakePhoto,
    },
    props: {
    	problemId: {
    		type: String
    	},
    	module: {
    		type: String
    	},
    	submitUrl: {
    		type: String
    	},
    	backUrl: {
    		type: String,
    		default: null
    	},
    	updateable: {
    		type: Boolean,
    		default: false
    	},
    	updateProblemApi: {
    		type: String
    	},
    	problemSendBack: {
    		type: Object
    	}
    },
    data: function() {
    	return {
    		sendBackRemarkShow: false,
    		sendBackRemark: '',
    		form: {
    			problemId: null,
                photos: [],
                remark: '',
                backReasonValue: null
            },
            deletePhotos: []
    	};
    },
    methods: {
    	changeBackReson: function(reason) {
    		if(reason == '其他') {
                this.sendBackRemarkShow = true;
    		} else {
                this.sendBackRemarkShow = false;
    		}
    		this.form.backReasonValue = reason;
        },
    	photoAdd: function(cdvPath) {
    		this.form.photos.push(cdvPath);
    	},
    	photoDelete: function(cdvPath) {
    		for(var i = 0; i < this.form.photos.length; i++) {
    			if(cdvPath == this.form.photos[i]) {
    				this.form.photos.splice(i, 1);
                    if(cdvPath.indexOf(this.module) > -1) {
                        this.deletePhotos.push(cdvPath);
                    }
    				break;
    			}
    		}
    	},
        ensureSendBackSubmit: function(){
        	var self = this;
            this.$f7.dialog.confirm("您确定退回？","",function () {
                 self.sendBackSubmit();
            });
        },
        sendBackSubmit: function(){
        	var self = this;
            if(self.form.backReasonValue != null && self.form.backReasonValue != ''){
                self.$f7.preloader.show();
                let promises = [];
            	var data = {
            		photos: []
            	};
                // 暂时未添加实测实量的Id
                if(self.module == 'localeCheck') {
                	data.checkQualityProblemId = self.problemId;
                    data.sendBackUserId = getUser().userId;
                } else if (self.module == 'qualityMeasure'){
                	data.qualityMeasureCheckQualityProblemId = self.problemId;
                }
                if(self.form.backReasonValue == '其它'){
                    if(self.sendBackRemark == ''){
                        data.sendBackRemark = '其它';
                    }else{
                        data.sendBackRemark = self.sendBackRemar;
                    }
                }else{
                    data.sendBackRemark = '整改不合格';
                }
                self.form.photos.forEach(photoPath => {
                	let promise = FileUtil.read(photoPath, 'image/jpeg').then(blob => {
                		let splits = photoPath.split("/");
                		let filename = splits[splits.length - 1];
                		return uploadImage(filename, blob);
                	}).then(result => {
                		data.photos.push({url: result.url});
                		return Promise.resolve();
                	});
                	promises.push(promise);
                });
                Promise.all(promises).then((blobs) => {
                	return request({
                		url: self.submitUrl,
                		method: 'post',
                		data: data
                	});
                }).then(result => {
                	self.$f7.preloader.hide();
                	self.$f7.dialog.alert(result.msg, '问题退回成功！');
                	if(self.backUrl != null) {
                		self.$f7router.back(self.backUrl,{force: true});
                	}
                	if(self.updateable) {
                		self.$emit(self.updateProblemApi, result.element);
                        self.$f7router.emit(self.updateProblemApi, result.element);
                	}
                	if(self.form.tid != null) {
                    	self.$emit('deleteProblemSendBack', self.form.tid);
                    	self.$f7router.emit('deleteProblemSendBack', self.form.tid);
                    }
                }).catch(error => {
        			console.error(error);
        			self.$f7.preloader.hide();
                	self.$f7.dialog.alert('', '问题退回失败！');
        		});
                
            }else{
                this.$f7.dialog.alert('请选择问题退回原因', '错误提示');
            }
        },
        saveTemporary: function() {
        	var self = this;
        	let promises = [];
        	self.deletePhotos.forEach(photo => {
    	        let promise = FileUtil.remove(photo).then(() => {
    	        	return Promise.resolve();
    	        }).catch((error) => {
    	        	console.error(error);
    	        	return Promise.resolve();
    	        });
    	        promises.push(promise);
    		});
        	Promise.all(promises).then(() => {
    			let promises = [];
    			self.form.photos.forEach(photo => {
    				let promise = null;
    				if(photo.indexOf(Common.directory().localeCheck) < 0) {
    					let splits = photo.split('/');
    					let filename = splits[splits.length - 1];
    					let to = Common.directory().base + Common.directory().localeCheck + filename;
    					promise = FileUtil.copy(photo, to);
    				} else {
    					promise = new Promise((resolve, reject) => {
    						resolve(photo);
    					});
    				}
                    promises.push(promise);
    			});
    			return Promise.all(promises);
    		}).then((paths) => {
    			let photos = [];
    			paths.forEach(path => {
    				photos.push(path);
    			});
    			self.form.photos = photos;
    			self.form.problemId = self.problemId;
        		this.$f7.dialog.confirm("是否确定暂存？", "", function(){
        			if(self.form.photos.length == 0) {
                        self.$f7.dialog.alert('没有需要暂存的图片 ', '错误');
            		    return;
                    }
            		self.$emit('saveTemporaryProblemSendBack', self.form);
                	self.$f7router.emit('saveTemporaryProblemSendBack', self.form);
                	self.$f7router.back();
        		});
    		}).catch(error => {
    			console.error(error);
    		});
        }
    },
    computed: {
    	reasons() {
    		return [
    			"整改不合格",
    			"其他"
    		];
    	}
    },
    watch: {
    	
    },
    created: function() {
    	
    },
    mounted: function() {
    	var self = this;
    	if(self.problemSendBack.photos.length != 0){
    		self.form.photos = self.problemSendBack.photos[0];
        	self.$refs.refTakePhoto.addPhotos(self.form.photos);
    	}
    	self.form.tid = self.problemSendBack.tid;
    	self.form.remark = self.problemSendBack.remark;
    	self.form.backReasonValue = self.problemSendBack.backReasonValue;
    }
}
</script>

<style scoped>

</style>